package com.huisang.controller;

import com.huisang.domain.Emp;
import com.huisang.service.EmpService;
import com.huisang.util.MD5Util;
import com.huisang.util.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;



@RestController
public class EmpController {

    @Autowired
    private EmpService empService;

    @PostMapping("/crm/reg")
    public ResponseEntity<Integer> reg(Emp emp) {

        emp.setPasswd(MD5Util.toMd5(emp.getPasswd()));

        int i = empService.addEmp(emp);
        ResponseEntity<Integer> responseEntity = new ResponseEntity<Integer>();
        if(i == -1) {
            responseEntity.setCode(200);
            responseEntity.setMessage("用户名已存在");
            responseEntity.setData(i);

            return responseEntity;
        }
        if(i == -2) {
            responseEntity.setCode(500);
            responseEntity.setMessage("注册失败，服务器发生错误");
            responseEntity.setData(i);

            return responseEntity;
        }
        responseEntity.setCode(200);
        responseEntity.setMessage("恭喜你，注册成功");
        responseEntity.setData(i);

        return responseEntity;
    }

    @PostMapping("/crm/login")
    public ResponseEntity<Integer> login(Emp emp) {
        emp.setPasswd(MD5Util.toMd5(emp.getPasswd()));
        ResponseEntity<Integer> responseEntity = new ResponseEntity<Integer>();
        int i = empService.login(emp);

        if(i == -1) {
            responseEntity.setCode(200);
            responseEntity.setMessage("密码不正确");
            responseEntity.setData(i);

            return responseEntity;
        }
        if(i == -2) {
            responseEntity.setCode(500);
            responseEntity.setMessage("没有此用户");
            responseEntity.setData(i);

            return responseEntity;
        }
        responseEntity.setCode(200);
        responseEntity.setMessage("登录成功");
        responseEntity.setData(i);

        return responseEntity;
    }
    @GetMapping("/crm/findEmpByEid")
    public ResponseEntity<Emp> findEmpByEid(Emp emp) {
        Emp emp1 = empService.findEmpByEid(emp);
        ResponseEntity<Emp> responseEntity = new ResponseEntity<Emp>();
        responseEntity.setCode(200);
        responseEntity.setMessage("OK");
        responseEntity.setData(emp1);
        return responseEntity;
    }
    @PostMapping("/crm/updatePassword")
    public ResponseEntity<Integer> updatePassword(Emp emp, String newpasswd){
        ResponseEntity<Integer> responseEntity = empService.updatePassword(emp, newpasswd);
        //放在service处理复杂业务
        return responseEntity;
    }
}
